﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HtmlAgilityPack;
using System.IO;

namespace autoBidProject
{
    class SBO
    {
        // html/body/table/tbody/tr/td[2]/table/tbody/tr/td[2]/select/option[2]
        private static System.Windows.Forms.HtmlDocument htmldoc;

        #region  Get event from SBO
        public static List<League> LoadFromSBO(System.Windows.Forms.HtmlDocument _htmldoc, bool bLiveEvent)
        {
            htmldoc = _htmldoc;
            if (bLiveEvent)
                return GetLiveEventFromSBO();
            return GetNonLiveEventFromSBO();
        }

        public static void Update(System.Windows.Forms.HtmlDocument _htmldoc)
        {
            htmldoc = _htmldoc;

            CheckViewMode();
            CheckRefreshSite();
        }

        private static void CheckRefreshSite()
        {
            System.Windows.Forms.HtmlDocument mainDocument = GetMainFrameHtmlDocument();
            if (mainDocument != null)
            {
                HtmlElement buttonFresh = null;
                if (Setting.bEventType)
                    buttonFresh = mainDocument.GetElementById("liveRefreshButton");
                else
                    buttonFresh = mainDocument.GetElementById("nonliveRefreshButton");

                if (buttonFresh != null)
                {
                    HtmlElement p = buttonFresh.Parent;
                    string s = p.GetAttribute("onclick");
                    if (s != "")
                    {
                        string innerText = buttonFresh.InnerText.Trim();
                        if (innerText != null)
                            if (innerText.CompareTo("Please wait") != 0)
                                p.InvokeMember("click");
                    }
                }
            }
        }

        private static void CheckViewMode()
        {
            System.Windows.Forms.HtmlDocument frameDoc = GetMainFrameHtmlDocument();
            if (frameDoc != null)
            {
                HtmlElement oddsMode = frameDoc.GetElementById("OddsMode");

                if (oddsMode != null)
                {
                    if (oddsMode.GetAttribute("selectedIndex") != "1")
                    {
                        oddsMode.SetAttribute("selectedIndex", "1");
                        oddsMode.InvokeMember("onchange");
                    }
                    else
                    {
                        oddsMode.SetAttribute("disabled", "true");   //oddsMode.Enabled = false;   // cái này cũng được
                    }
                }
            }
        }

        private static List<League> GetLiveEventFromSBO()
        {
            HtmlElement table = GetLiveTable();
            if (table != null)
            {
                HtmlAgilityPack.HtmlDocument agiDoc = new HtmlAgilityPack.HtmlDocument();
                if (table.InnerHtml != null)
                {
                    agiDoc.LoadHtml(table.InnerHtml);
                    if (agiDoc != null)
                        return GetEventFromSBO(agiDoc);
                }
            }
            return null;
        }
       
        private static List<League> GetNonLiveEventFromSBO()
        {
            HtmlElement table = GetNoneLiveTable();
            if (table != null)
            {
                HtmlAgilityPack.HtmlDocument agiDoc = new HtmlAgilityPack.HtmlDocument();
                agiDoc.LoadHtml(table.InnerHtml);
                if (agiDoc != null)
                    return GetEventFromSBO(agiDoc);
            }
            return null;
        }

        private static List<League> GetEventFromSBO(HtmlAgilityPack.HtmlDocument agiDoc)
        {
            List<League> leagues = null;
            if (agiDoc != null)
            {
                ///table/tbody/tr/td/table/tbody/tbody
                HtmlNodeCollection nodes = agiDoc.DocumentNode.SelectNodes("/table/tbody/tr/td/table/tbody/tbody");
                if (nodes != null)
                {
                    leagues = new List<League>();
                    League league = null;
                    for (int i = 0; i < nodes.Count; i++)
                    {
                        String leagueName = "";
                        if (IsSBOLeague(nodes[i], ref leagueName))
                        {
                            if (league != null)
                                leagues.Add(league);
                            league = new League(leagueName);
                        }
                        else if (IsSBOEvent(nodes[i]))
                        {
                            Event e = LoadEvent(nodes[i]);
                            if (league == null)
                                league = new League("xxx");
                            league.Add(e);
                        }
                    }
                    if (league != null)
                        leagues.Add(league);
                }
            }
            return leagues;
        }

        private static Event LoadEvent(HtmlNode eventNode)
        {
            Event e = new Event();
            e.xpath = eventNode.XPath;

            HtmlNodeCollection elements = eventNode.SelectNodes("tr[1]/td[2]/span");
            if(elements != null)
            {
                e.name_home = elements[0].InnerText;
                e.name_away = elements[1].InnerText;
            }

            elements = eventNode.SelectNodes("tr[1]/td[5]/span");
            if (elements != null)
                e.ft_hdp = elements[0].InnerText.Replace("&nbsp;", ""); ;

            elements = eventNode.SelectNodes("tr[1]/td[11]/span");
            if (elements != null)
                e.fh_hdp = elements[0].InnerText.Replace("&nbsp;", ""); ;

            string id = "";
            e.ft_home  = GetFloat(eventNode, "tr/td[6]/span", ref id);
            e.ft_home_id = id;
            e.ft_home_xpath = ChoseXpath(e.ft_home, "tr/td[6]/span");

            e.ft_away = GetFloat(eventNode, "tr/td[7]/span", ref id);
            e.ft_away_id = id;
            e.ft_away_xpath = ChoseXpath(e.ft_away, "tr/td[7]/span");

            e.ft_over = GetFloat(eventNode, "tr/td[9]/span", ref id);
            e.ft_over_id = id;
            e.ft_over_xpath = ChoseXpath(e.ft_over, "tr/td[9]/span");

            e.ft_under = GetFloat(eventNode, "tr/td[10]/span", ref id);
            e.ft_under_id = id;
            e.ft_under_xpath = ChoseXpath(e.ft_under, "tr/td[10]/span");

            e.fh_home = GetFloat(eventNode, "tr/td[12]/span", ref id);
            e.fh_home_id = id;
            e.fh_home_xpath = ChoseXpath(e.fh_home, "tr/td[12]/span");

            e.fh_away = GetFloat(eventNode, "tr/td[13]/span", ref id);
            e.fh_away_id = id;
            e.fh_away_xpath = ChoseXpath(e.fh_away, "tr/td[13]/span");

            e.fh_over = GetFloat(eventNode, "tr/td[15]/span", ref id);
            e.fh_over_id = id;
            e.fh_over_xpath = ChoseXpath(e.fh_over, "tr/td[15]/span");

            e.fh_under = GetFloat(eventNode, "tr/td[16]/span", ref id);
            e.fh_under_id = id;
            e.fh_under_xpath = ChoseXpath(e.fh_under, "tr/td[16]/span");

            return e;
        }

        private static float GetFloat(HtmlNode node, string xpath, ref string id)
        {
            HtmlNodeCollection exist = node.SelectNodes(xpath);
            if(exist != null)
                try
                {
                    float value = float.Parse(exist[0].InnerText);
                    id = exist[0].Attributes["id"].Value;
                    if (id == null)
                        id = "";
                    return value;
                }
                catch (Exception)
                {
                    id = "";
                    return -1;
                }
            return -1;
        }

        private static string ChoseXpath(float value, string xpath)
        {
            if (value == -1)
                return "";
            return xpath;
        }

        private static bool IsSBOLeague(HtmlNode node, ref String leagueName)
        {
            HtmlNodeCollection league = node.SelectNodes("tr/td/span[@class=\"LeagueRowName\"]");
            if (league != null)
                leagueName = league[0].InnerText;
            return league != null;
        }

        private static bool IsSBOEvent(HtmlNode node)
        {
            HtmlNodeCollection league = node.SelectNodes("tr[@class=\"LiveEventRow\"  or @class=\"NonliveEventRow\" or @class=\"NonliveEventAlternateRow\"]");
            return league != null;
        }

        public static HtmlElement GetTableEvents()
        {
            if (Setting.bEventType == true)
                return GetLiveTable();
            return GetNoneLiveTable();
        }

        private static HtmlElement GetLiveTable()
        {
            System.Windows.Forms.HtmlDocument htmlDoc = GetMainFrameHtmlDocument();
            if (htmlDoc != null)
                return htmlDoc.GetElementById("levents");
            return null;
        }

        private static HtmlElement GetNoneLiveTable()
        {
            System.Windows.Forms.HtmlDocument htmlDoc = GetMainFrameHtmlDocument();
            if (htmlDoc != null)
                return htmlDoc.GetElementById("events");
            return null;
        }


        #endregion

        #region Tương tác với web

        #endregion

        
        private static System.Windows.Forms.HtmlDocument GetMainFrameHtmlDocument()
        {
            if (htmldoc != null)
            {
                HtmlWindow mainFrame = GetFrame(htmldoc, "mainFrame");
                if (mainFrame != null)
                    return mainFrame.Document;
            }
            return null;
        }

        private static HtmlWindow GetFrame(System.Windows.Forms.HtmlDocument htmldoc, string frameId)
        {
            if (htmldoc != null)
            {
                if (htmldoc.Window.Frames.Count > 0)
                    return htmldoc.Window.Frames[frameId];
            }
            return null;
        }


    }
}
